package cn.com.panda;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.FragmentTransaction;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.FileUtils;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import cn.com.hesc.library.ActionListener;
import cn.com.hesc.library.ActionType;
import cn.com.hesc.library.ExtendsWebView;
import cn.com.hesc.library.JavaScriptInterface;
import cn.com.hesc.library.MessageHandler;
import cn.com.hesc.library.WebViewClientSelf;
import cn.com.hesc.library.entity.StorageBean;
import cn.com.panda.base.BaseActivity;
import cn.com.panda.conf.Config;
import cn.com.panda.multiplepic.MultiplePicActivity;
import cn.com.panda.utils.SharedPreferencesUtil;

public class MainActivity extends BaseActivity implements ActionListener {

    private ExtendsWebView webview;
    /**实现 input type=file******************************/
    private ValueCallback<Uri> mUploadMessage;
    public ValueCallback<Uri[]> uploadMessage;
    public static final int REQUEST_SELECT_FILE = 100;
    private final static int FILECHOOSER_RESULTCODE = 101;
    public static final int REQUEST_CAPTURE_FILE = 102;
    /**input file 涉及到的选择操作*/
    private FrameLayout mediatoolbar;
    private TextView tocapture,tomediachoose,navright;
    private ImageView devider;
    /**拍照相关功能**/
    private String mediaUrl;
    private MessageHandler captureMessageHandler;
    private static final int TAKE_PICTURE = 4;
    private Uri imageUri;
    /***选择图片**/
    private MessageHandler multiPictureMessageHandler;
    private static final int MULTIPLE_CHOISE = 5;
    private static final int PREVIEW_PICTURE = 6;
    /*******************************************************/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

        //目前首页为空，设置为3秒后跳转到假设备----------------
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Bundle bundle = new Bundle();
                bundle.putString("btdevice","BTEST001");
                toActivity(BlueToothActivity.class,bundle);
            }
        },3000L);
    }

    @Override
    protected void checkPermissionResult(String[] permissions, int[] grantResults) {

    }

    private void initView() {
        webview = findViewById(R.id.webview);
        webviewSetting();
        if(!TextUtils.isEmpty(Config.mainUrl))
            webview.loadUrl(Config.mainUrl);

        mediatoolbar = (FrameLayout) findViewById(R.id.mediatoolbar);
        mediatoolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                }
                mediatoolbar.setVisibility(View.GONE);
            }
        });
        tocapture = (TextView)findViewById(R.id.tocapture);
        tocapture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String[] PERMISSIONS = {Manifest.permission.CAMERA};
                if (ContextCompat.checkSelfPermission(mContext, PERMISSIONS[0]) != PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(MainActivity.this,PERMISSIONS,999);
                    return;
                }

                mediatoolbar.setVisibility(View.GONE);
                //打开照相机
                Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if(Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q){
                    imageUri = createImageUri();
                }else{
                    imageUri = getOutputMediaFileUri(mContext);
                }
                openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                //Android7.0添加临时权限标记，此步千万别忘了
                openCameraIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                startActivityForResult(openCameraIntent, REQUEST_CAPTURE_FILE);
            }
        });
        tomediachoose = (TextView)findViewById(R.id.tomediachoose);
        tomediachoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] PERMISSIONS = {Manifest.permission.READ_EXTERNAL_STORAGE};
                if (ContextCompat.checkSelfPermission(mContext, PERMISSIONS[0]) != PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(MainActivity.this,PERMISSIONS,999);
                    return;
                }
                Intent it = new Intent(mContext, MultiplePicActivity.class);
                Bundle bl = new Bundle();
                bl.putInt("piccount",1);
                it.putExtras(bl);
                startActivityForResult(it,REQUEST_SELECT_FILE);
            }
        });
    }

    /**
     * 创建图片地址uri,用于保存拍照后的照片 Android 10以后使用这种方法
     */
    private Uri createImageUri() {
        String status = Environment.getExternalStorageState();
        // 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            return getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
        } else {
            return getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, new ContentValues());
        }
    }

    private static Uri getOutputMediaFileUri(Context context) {
        File mediaFile = null;
        String cameraPath;
        try {
            File mediaStorageDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {
                    return null;
                }
            }
            mediaFile = new File(mediaStorageDir.getPath()
                    + File.separator
                    + "Pictures/temp.jpg");//注意这里需要和filepaths.xml中配置的一样
            cameraPath = mediaFile.getAbsolutePath();

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {// sdk >= 24  android7.0以上
            Uri contentUri = FileProvider.getUriForFile(context,
                    context.getApplicationContext().getPackageName() + ".fileProvider",//与清单文件中android:authorities的值保持一致
                    mediaFile);//FileProvider方式或者ContentProvider。也可使用VmPolicy方式
            return contentUri;

        } else if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
            Uri contentUri = FileProvider.getUriForFile(context,
                    context.getApplicationContext().getPackageName() + ".fileProvider",//与清单文件中android:authorities的值保持一致
                    mediaFile);//FileProvider方式或者ContentProvider。也可使用VmPolicy方式
            return uriToFileApiQ(context,contentUri);
        }
        else {
            return Uri.fromFile(mediaFile);//或者 Uri.isPaise("file://"+file.toString()

        }
    }

    /**
     * Android 10 以上适配
     * @param context
     * @param uri
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.Q)
    private static Uri uriToFileApiQ(Context context, Uri uri) {
        File file = null;
        //android10以上转换
        if (uri.getScheme().equals(ContentResolver.SCHEME_FILE)) {
            file = new File(uri.getPath());
        } else if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
            //把文件复制到沙盒目录
            ContentResolver contentResolver = context.getContentResolver();
            Cursor cursor = contentResolver.query(uri, null, null, null, null);
            if (cursor.moveToFirst()) {
                String displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                try {
                    InputStream is = contentResolver.openInputStream(uri);
                    File cache = new File(context.getExternalCacheDir().getAbsolutePath(), Math.round((Math.random() + 1) * 1000) + displayName);
                    FileOutputStream fos = new FileOutputStream(cache);
                    FileUtils.copy(is, fos);
                    file = cache;
                    fos.close();
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Uri.fromFile(file);
    }

    private void webviewSetting() {
        webview.getSettings().setJavaScriptEnabled(true);
        webview.setWebViewClient(new WebViewClientSelf(this, new WebViewClientSelf.HttpStatusListener() {
            @Override
            public void onSuccess() {
            }

            @Override
            public void onError(int code) {
            }
        }));
        webview.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, final int newProgress) {
            }

            @Override
            public void onShowCustomView(View view, CustomViewCallback callback) {

            };

            @Override
            public void onHideCustomView() {

            }

            //实现 input type=file的做法 可直接拷贝 Android  >= 3.0
            protected void openFileChooser(ValueCallback uploadMsg, String acceptType)
            {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
            }
            // For Lollipop 5.0+ Devices 实现 input type=file的做法 可直接拷贝 Android >= 5.0
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, final FileChooserParams fileChooserParams)
            {
                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                }
                uploadMessage = filePathCallback;
                mediatoolbar.setVisibility(View.VISIBLE);
                tocapture.setVisibility(View.VISIBLE);
                tomediachoose.setVisibility(View.VISIBLE);
                return true;
            }
            //For Android 4.1 only 实现 input type=file的做法 可直接拷贝 Android  >= 4.1
            protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
            {
                mUploadMessage = uploadMsg;
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("*/*");
                startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE);
            }

            //实现 input type=file的做法 可直接拷贝 Android < 3.0
            protected void openFileChooser(ValueCallback<Uri> uploadMsg)
            {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
            }
        });
        webview.addJavascriptInterface(new JavaScriptInterface(this),"Native");
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public void onAction(ActionType actionType, String params) {
        try {
            JSONObject jsonObject = new JSONObject(params);
            MessageHandler messageHandler = new MessageHandler();
            messageHandler.setUniqueId(jsonObject.getString("callbackId"));
            switch (actionType){
                case DEVICE_GETDATA:
                    getPrivateData(messageHandler,params);
                    break;
                case DEVICE_SAVEDATA:
                    setPrivateData(messageHandler,params);
                    break;
                case DEVICE_REMOVEDATA:
                    removePrivateData(messageHandler,params);
                    break;
                case DEVICE_OPENWEB:
                    openActivity(messageHandler,params);
                    break;
            }

        }catch (Exception e){
            e.printStackTrace();
        }

    }

    private void openActivity(MessageHandler messageHandler, String params) {
        try{
            JSONObject jsonObject = new JSONObject(params);
            String urlstr = jsonObject.optString("url");
            //打开蓝牙界面
            if("bluetooth".equals(urlstr)){
                Bundle bundle = new Bundle();
                bundle.putString("btdevice","BseeraA001");
                toActivity(BlueToothActivity.class,bundle);
            }else if(urlstr.contains("http") || urlstr.contains("https")){
                //页面跳转href
                Bundle bundle = new Bundle();
                bundle.putString("url",urlstr);
                toActivity(WebViewActivity.class,bundle);
            }
            webview.excuteJs(messageHandler);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void getPrivateData(MessageHandler messageHandler, String params) {
        SharedPreferencesUtil sharedPreferencesUtil = new SharedPreferencesUtil(mContext);
        try {
            JSONObject jsonObject = new JSONObject(params);
            String param = jsonObject.getString("name");
            String value = sharedPreferencesUtil.getString(param);
            StorageBean storageBean = new StorageBean();
            storageBean.setResult(true);
            storageBean.setValue(value);
            messageHandler.setSuccess(true);
            messageHandler.setRes(storageBean);
            webview.excuteJs(messageHandler);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void removePrivateData(MessageHandler messageHandler, String params) {
        SharedPreferencesUtil sharedPreferencesUtil = new SharedPreferencesUtil(mContext);
        try {
            JSONObject jsonObject = new JSONObject(params);
            if(jsonObject.has("name")){
                sharedPreferencesUtil.saveString(jsonObject.getString("name"),"");
                webview.excuteJs(messageHandler);
            }else{
                String error = "缺乏key";
                messageHandler.setRes(error);
                messageHandler.setSuccess(false);
                webview.excuteJs(messageHandler);
            }
        }catch (Exception e){
            e.printStackTrace();
            String error = "数据格式错误";
            messageHandler.setRes(error);
            messageHandler.setSuccess(false);
            webview.excuteJs(messageHandler);
        }
    }

    private void setPrivateData(MessageHandler messageHandler, String params) {
        SharedPreferencesUtil sharedPreferencesUtil = new SharedPreferencesUtil(mContext);
        try {
            JSONObject jsonObject = new JSONObject(params);
            if(jsonObject.has("name") && jsonObject.has("value")){
                sharedPreferencesUtil.saveString(jsonObject.getString("name"),jsonObject.getString("value"));
                webview.excuteJs(messageHandler);
            }else{
                String error = "缺乏key或者value";
                messageHandler.setRes(error);
                messageHandler.setSuccess(false);
                webview.excuteJs(messageHandler);
            }
        }catch (Exception e){
            e.printStackTrace();
            String error = "数据格式错误";
            messageHandler.setRes(error);
            messageHandler.setSuccess(false);
            webview.excuteJs(messageHandler);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case REQUEST_SELECT_FILE:
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                {
                    if (uploadMessage == null)
                        return;
                    Bundle bl = data.getExtras();
                    List<String> list = bl.getStringArrayList("pics");
                    if(list == null)
                        return;
                    Uri[] uris = new Uri[list.size()];
                    for (int i = 0; i < list.size(); i++) {
                        File mediaFile = new File(list.get(i));
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {// sdk >= 24  android7.0以上
                            Uri contentUri = FileProvider.getUriForFile(mContext,
                                    mContext.getApplicationContext().getPackageName() + ".fileProvider",//与清单文件中android:authorities的值保持一致
                                    mediaFile);//FileProvider方式或者ContentProvider。也可使用VmPolicy方式
                            uris[i] = contentUri;
                        } else {
                            uris[i] = Uri.fromFile(mediaFile);//或者 Uri.isPaise("file://"+file.toString()

                        }
                    }
                    uploadMessage.onReceiveValue(uris);
                    uploadMessage = null;

                    mediatoolbar.setVisibility(View.GONE);
                }
                break;
            case REQUEST_CAPTURE_FILE:
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                {
                    if (uploadMessage == null)
                        return;
                    Uri[] uris = new Uri[1];
                    uris[0] = imageUri;
                    if(resultCode == RESULT_OK)
                        uploadMessage.onReceiveValue(uris);
                    else
                        uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                    mediatoolbar.setVisibility(View.GONE);
                }
                break;
        }

    }
}